package com.example.finalhomework.thirdhomework

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import coil.ImageLoader
import coil.compose.rememberAsyncImagePainter
import coil.decode.GifDecoder
import coil.request.ImageRequest
import com.example.finalhomework.R
import com.example.finalhomework.thirdhomework.FifthViewModel

@Composable
fun FifthScreen_3(navController: NavHostController = rememberNavController(), viewModel: FifthViewModel = viewModel()) {
    // 从 ViewModel 中获取秒数和计时器运行状态
    val seconds by viewModel::seconds
    val running by viewModel::running

    // 获取当前的上下文
    val context = LocalContext.current

    // 创建一个 ImageLoader，用于加载 GIF 图像
    val imageLoader = ImageLoader.Builder(context)
        .components {
            add(GifDecoder.Factory()) // 添加 GIF 解码器
        }
        .build()

    // 加载静态图像资源
    val staticImagePainter = painterResource(id = R.drawable.static_animation1)

    // 创建一个 ImageRequest，用于请求 GIF 图像
    val gifImageRequest = ImageRequest.Builder(context)
        .data(R.raw.animation1) // 设置 GIF 图像资源
        .build()

    // 使用 rememberAsyncImagePainter 加载 GIF 图像（提前加载，可以提高运行的性能）
    val gifImagePainter = rememberAsyncImagePainter(
        model = gifImageRequest,
        imageLoader = imageLoader
    )

    // 使用 LaunchedEffect 监听计时器运行状态的变化
    //（LaunchedEffect 会在组合时启动一个新的协程，用于执行异步操作或副作用。当 running 发生变化时，这段代码会重新执行）
    LaunchedEffect(running) {
        if (running) {
            imageLoader.enqueue(gifImageRequest) // 如果计时器正在运行，则加载 GIF 图像
        }
    }

    // 根据计时器的运行状态选择显示的图像
    val painter = if (running) {
        gifImagePainter // 计时器运行时显示 GIF 图像
    } else {
        staticImagePainter // 计时器停止时显示静态图像
    }

    // 创建一个垂直排列的列布局
    Column(
        modifier = Modifier
            .fillMaxSize() // 填充整个屏幕
            .padding(16.dp), // 设置内边距为 16dp
        verticalArrangement = Arrangement.Center, // 垂直居中排列
        horizontalAlignment = Alignment.CenterHorizontally // 水平居中排列
    ) {
        // 计算小时、分钟和秒数
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val secs = seconds % 60
        // 格式化时间字符串
        val time = String.format("%02d:%02d:%02d", hours, minutes, secs)
        Log.d("FifthScreen_3", "Formatted time: $time")

        // 显示图像
        Image(painter = painter, contentDescription = null)
        Spacer(modifier = Modifier.height(16.dp)) // 间隔 16dp 的空白
        // 显示计时器时间
        Text(text = time, modifier = Modifier.padding(bottom = 16.dp))
        // 创建一个水平排列的行布局
        Row {

            Button(onClick = {  // 开始按钮，点击时启动计时器
                viewModel.startTimer()
                Log.d("FifthScreen_3", "Start button clicked")
            }, modifier = Modifier.padding(end = 8.dp)) {
                Text("Start")
            }

            Button(onClick = {  // 停止按钮，点击时停止计时器
                viewModel.stopTimer()
                Log.d("FifthScreen_3", "Stop button clicked")
            }, modifier = Modifier.padding(end = 8.dp)) {
                Text("Stop")
            }

            Button(onClick = {  // 重置按钮，点击时重置计时器
                viewModel.resetTimer()
                Log.d("FifthScreen_3", "Restart button clicked")
            }) {
                Text("Restart")
            }
        }
        Log.d("FifthScreen_3", "Composable function executed")
    }
}

@Preview(showBackground = true)
@Composable
fun FifthScreenPreview() {
    FifthScreen_3()
}